//
//  CommentsViewController.m
//  项目A_百思不得姐
//
//  Created by wudongyang on 16/5/31.
//  Copyright © 2016年 wudongyang. All rights reserved.
//

#import "CommentsViewController.h"
#import "CommentsTableViewCell.h"
#import <AFNetworking.h>
#import "UIImageView+WebCache.h"
#import "LandingViewController.h"
static NSString *const indexCell = @"reuse";
@interface CommentsViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong)UITableView *myTableView;
@property(nonatomic, strong)NSMutableArray *allArray;
@property(nonatomic, strong)UIView *bigView;
@property(nonatomic, strong)UIImageView *myImageView;
@property(nonatomic, strong)UIButton *VideoButton;
@property(nonatomic, strong)UILabel *TextLabel;


@end

@implementation CommentsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.allArray = [NSMutableArray array];
    [self getData];
    self.navigationItem.title = @"评论";
    
    UIBarButtonItem *CollectionButton = [UIBarButtonItem itemWithImage:@"MainTagSubIcon" highImage:@"MainTagSubIconClick" target:self action:@selector(CollectionButtonAction:)];
    self.navigationItem.rightBarButtonItem = CollectionButton;
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.myTableView];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.myTableView registerClass:[CommentsTableViewCell class] forCellReuseIdentifier:indexCell];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.bigView = [[UIView alloc] init];
    self.bigView.frame = CGRectMake(0, 0, self.view.frame.size.width, 265);
    self.bigView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.bigView];
    
    // 创建标题label
    self.TextLabel = [[UILabel alloc] init];
    self.TextLabel.frame = CGRectMake(10, 0, self.bigView.frame.size.width, 30);
    self.TextLabel.backgroundColor = [UIColor clearColor];
    self.TextLabel.text = self.myText;
    [self.bigView addSubview:self.TextLabel];
    
    self.myImageView = [[UIImageView alloc] init];
    self.myImageView.backgroundColor = [UIColor blackColor];
    self.myImageView.frame = CGRectMake(0, 30, self.bigView.frame.size.width, self.bigView.frame.size.height - 30);
    self.myImageView.userInteractionEnabled = YES;
    
    // 创建URL
    self.url = [NSURL URLWithString:self.myUrl];
    
    // 构造AVPlayerItem对象
    self.item = [[AVPlayerItem alloc] initWithURL:self.url];
    // 初始化player
    self.VideoPayer = [[AVPlayer alloc] initWithPlayerItem:self.item];
    // 需要一个AVPlayerLayer对象
    self.isLayer = [AVPlayerLayer playerLayerWithPlayer:self.VideoPayer];
    // 播放窗口坐标大小
    self.isLayer.frame = CGRectMake(0, 0, self.myImageView.frame.size.width, self.myImageView.frame.size.height);
    
    self.isLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    //添加到屏幕上显示
    [self.myImageView.layer addSublayer:self.isLayer];
    
    
    if ([self.myType isEqualToString:@"gif"]) {
        [self.myImageView sd_setImageWithURL:[NSURL URLWithString:self.myGif] placeholderImage:[UIImage imageNamed:@"tupian1.jpeg"]];
    }else if ([self.myType isEqualToString:@"video"]){
        [self.myImageView sd_setImageWithURL:[NSURL URLWithString:self.myVideo] placeholderImage:[UIImage imageNamed:@"tupian1.jpeg"]];
        // 视频播放按钮
        self.VideoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.VideoButton setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        // 播放按钮的点击
        [self.VideoButton addTarget:self action:@selector(VideoButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.myImageView addSubview:self.VideoButton];
        // 视频播放按钮坐标大小
        self.VideoButton.frame = CGRectMake(0, 0, 100, 100);
        self.VideoButton.center = CGPointMake(self.myImageView.frame.size.width / 2, self.myImageView.frame.size.height / 2);
    }else {
        [self.myImageView sd_setImageWithURL:[NSURL URLWithString:self.myImage] placeholderImage:[UIImage imageNamed:@"tupian1.jpeg"]];
    }
    [self.bigView addSubview:self.myImageView];
    
    
    
    self.myTableView.tableHeaderView = self.bigView;
    
    
    
    // Do any additional setup after loading the view.
}
-(void)getData{
    NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=dataList&appname=bs0315&asid=986C8830-1671-4071-BB49-37A7E7F66615&c=comment&client=iphone&data_id=%@&device=ios%%20device&from=ios&hot=1&jbk=0&mac=&market=&openudid=21c4a1f4b37d431985e8e05255fdfec2bcb43c5a&page=1&per=50&udid=&uid=18333270&ver=4.1",self.myID];
//    DSLog(@"%@",self.myID);
    //GET请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        NSMutableArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            CommentsModel *commentsModel = [CommentsModel new];
            [commentsModel setValuesForKeysWithDictionary:dic];
            [self.allArray addObject:commentsModel];
        }
        
        [self.myTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indexCell];
    CommentsModel *model = self.allArray[indexPath.row];
    cell.commentModel = model;
    cell.selectionStyle = 0;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentsModel *commentsModel = [self.allArray objectAtIndex:indexPath.row];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17],NSFontAttributeName, nil];
    CGRect rect = [commentsModel.content boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height + 70;
}

-(void)VideoButtonAction:(UIButton *)button{
    DSLog(@"我是视频播放按钮的点击方法");
    
    
    self.myImageView.image = nil;
    if (self.VideoButton.selected == 0) {
        [self.VideoPayer play];
        [self.VideoButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        
    }else {
        [self.VideoPayer pause];
        [self.VideoButton setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    }
    self.VideoButton.selected = !self.VideoButton.selected;
    
}
// 收藏按钮点击方法
-(void)CollectionButtonAction:(UIBarButtonItem *)item{
    DSLog(@"我是收藏按钮点击方法");
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *isLogin = [defaults objectForKey:@"isLogin"];
    NSString *userName = [defaults objectForKey:@"userName"];
    
    NSMutableArray *array = [[DataFMDBHandle shareDatHandle] selectAllCollecData:userName withCompare:NO];
    
    if ([isLogin isEqualToString:@"0"]) {
        LandingViewController *lanVC = [[LandingViewController alloc] init];
        [self presentViewController:lanVC animated:YES completion:^{
            
            
        }];
    }
        else if ([isLogin isEqualToString:@"1"]){

        if ([array containsObject:self.myText]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"这个收藏过了" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                
            }]];
            [self presentViewController:alert animated:YES completion:^{
                
                
            }];
        }
        else {
            self.MineModel = [[MineCollectModel alloc]init];
            // 把值放到新建收藏model
            self.MineModel.title = self.myText;
            self.MineModel.collectId = self.myID;
            self.MineModel.Image = self.myImage;
            self.MineModel.Gif = self.myGif;
            self.MineModel.Video = self.myVideo;
            self.MineModel.Type = self.myType;
            self.MineModel.Url = self.myUrl;
            
            [[DataFMDBHandle shareDatHandle] insertCollectData:self.MineModel withUserName:userName];
            
            DSLog(@"%@",self.MineModel.title);
            
        }
    
    }
    

}

@end
